package com.leetBook.Krahets.array;

import org.junit.Test;

public class MyAtoi {
    public int myAtoi(String str) {
        // 转换为字符数组
        char[] chars = str.toCharArray();

        boolean flag = false;
        StringBuilder num = new StringBuilder();
        for (char c: chars) {
            // 判断是否到达开始位置，+ - 或 数字，flag = true
            if (!flag && (c == '+' || c== '-' || c<=9)){
                flag = true;

                num.append(c);
            }

            // flag = true 开始处理，获取数字，不为数字时，跳出循环
            if (flag){
                if ((c >= 0 && c<=9)){
                    num.append(c);
                }else {
                    break;
                }
            }
        }

        if (num.length() == 0){
            return 0;
        }

        // 判断数字是否在范围内，不在范围，返回范围最大值
        Integer integer = Integer.valueOf(num.toString());

        int min = -2^31;
        int max = 2^31-1;
        if (integer < min){
            return min;
        }else if (integer > max){
            return max;
        }

        return integer;
    }

    @Test
    public void fun(){
        System.out.println(myAtoi("42"));
        System.out.println(myAtoi("   -42"));
        System.out.println(myAtoi("4193 with words"));
        System.out.println(myAtoi("  -23223+3"));
    }
}
